<template>
    <div class="content">
      <n-modal v-model:show="showModal">
        <n-card
          style="width: 600px"
          title="添加电动车"
          :bordered="true"
          role="dialog"
          aria-modal="true"
        >
        <n-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
          <n-form-item label="经度" path="machineLongitude">
            <n-input v-model:value="formData.machineLongitude" type="text" placeholder="请输入经度" />
          </n-form-item>

          <n-form-item label="纬度" path="machineLatitude">
            <n-input v-model:value="formData.machineLatitude" type="text" placeholder="请输入纬度" />
          </n-form-item>

          <n-button style="margin-top: 20px; margin-left: 250px;" type="info" @click="addMachine">确定</n-button>
        </n-form>
        </n-card>
      </n-modal>
      
      <n-button type="info" @click="downloadCsv">导出CSV文件</n-button>
      <n-modal-provider><n-button type="info" style="margin-left: 40px" @click="showModelClick">添加新的电动车</n-button></n-modal-provider>
      <div v-if="loading" style="display: flex; justify-content: center; margin-top: 70px;">
      <PageLoader />
      </div>
      <div class="filters" style="margin-top: 20px;">
      <n-select
        v-model:value="selectedArea"
        :options="areaOptions"
        placeholder="筛选区域"
        style="width: 200px; margin-right: 20px;" 
        clearable="true"
      />
      <n-select
        v-model:value="selectedStatus"
        :options="statusOptions"
        placeholder="筛选状态"
        style="width: 200px;"
        clearable="true"
      />
      <n-input placeholder="电动车编号" style="width: 300px; margin-left: 20px" v-model:value="query"></n-input>

      
      <n-button type="info" @click="fetchMachineList">查询</n-button>
      
    </div>
    <n-dialog-provider>
        <n-data-table
          ref="tableRef"
          :columns="columns"
          :data="machineList"
          :pagination="paginationReactive"
          :bordered="true"
          :scroll-x="true"
          :row-key="rowKey"
          striped
          style="margin-top: 40px; max-height: 800px;"
          :get-csv-cell="getCsvCell"
          :get-csv-header="getCsvHeader"
        />
      </n-dialog-provider>
    </div>
  </template>
  
  <script setup>
  import { h, onMounted, reactive, ref,createVNode } from "vue";
  import { NButton, NDataTable, NTag, NCard,NModal,NModalProvider,NForm,NFormItem,NInput,NSelect,NIconWrapper,NIcon,NDialogProvider,createDiscreteApi } from "naive-ui";
  import axiosInstance from "@/utils/axios";
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { usemsgStore } from "@/stores/msgwrapper";
  import PageLoader from "@/components/PageLoader.vue";
  import { Motorbike,TrashOff, CloudUpload} from '@vicons/tabler';
  import MachineStart from "@/components/MachineStart.vue";
  
  // 引入响应式数据
  const msgStore = usemsgStore()
  const {sendMessage} = msgStore
  const tableRef = ref(null);
  const maps = reactive(new Map()); // 使用Map存储每个行的地图实例
  const showModal = ref(false)
  const formRef = ref(null);
  const formData = reactive({
    machineLongitude: "",
    machineLatitude: "",
  });
  const {dialog} = createDiscreteApi(["dialog"]);



  const selectedArea = ref(null);
  const selectedStatus = ref(null);
  const query = ref(null);
  const areaOptions = reactive([]);
  // 筛选状态选项
  const statusOptions = [
    { label: "空闲中", value: 1 },
    { label: "正在骑行中", value: 0 },
    { label: "异常状态", value: 2 },
    { label: "停止中", value: 3 },
  ];

  const formRules = reactive({
    machineLongitude: [
      { required: true, message: "经度不能为空", trigger: "blur" }
    ],
    machineLatitude: [
      { required: true, message: "纬度不能为空", trigger: "blur" }
    ]
  });


  const rowKey = (row) => row.machine_id;
  
  // 为每个展开行生成一个唯一ID
  const generateContainerId = (machineId) => {
    return `container-${machineId}`;
  };
  
  // 初始化地图函数
  const initMap = (id, position, containerId) => {
    AMapLoader.load({
      key: "1cfd3a771aaf9dd11aa95a7472644c7e",  // API Key
      version: "2.0",  // 地图版本
      plugins: [],
    }).then((AMap) => {
      const map = new AMap.Map(containerId, {
        viewMode: "2D",   // 2D模式
        zoom: 12,         // 缩放级别
        center: position,  // 初始中心位置
      });
  
      const marker = new AMap.Marker({
        position: position,  // 设置标记位置
        title: `电动车设备ID: ${id}`,  // 标记标题
      });
  
      map.add(marker);  // 将标记添加到地图上
      maps.set(containerId, map);  // 存储地图实例
    }).catch((error) => {
      console.error("AMap SDK 加载失败:", error);
    });
  };

  const showModelClick= () =>{
    showModal.value = true
    formData.machineLatitude = '',
    formData.machineLongitude = ''
  };
  
  // 生成列配置
  const columns = createColumns();
  
  // 创建列定义
  function createColumns() {
    return [
      {
        type: "expand",
        renderExpand: (rowData) => {
          const containerId = generateContainerId(rowData.machine_id); // 为当前行生成唯一ID
          initMap(rowData.machine_id, rowData.machine_point, containerId); // 初始化地图
          return h(NCard, { id: containerId,style:{width:'100%',height:'200px'} }, h('div', {}));  // 渲染地图容器
        }
      },
      {
        title: "创建时间",
        key: "create_time",
      },
      {
        title: "上一次触发时间",
        key: "update_time",
      },
      {
        title: "电动车编号",
        key: "machine_id",
        width: 100,
        ellipsis: { tooltip: true },
      },
      {
        title: "电动车所在经纬度",
        key: "machine_point",
        width: 100,
        ellipsis: { tooltip: true },
        render(row) {
          return `经度: ${row.machine_point[0]}, 纬度: ${row.machine_point[1]}`;
        },
      },
      {
        title: "电动车电量",
        key: "machine_battery",
        render(row) {
          const batteryType = row.machine_battery > 20 ? "success" : "error";
          return h(
            NTag,
            { type: batteryType, bordered: false },
            `${row.machine_battery}%`
          );
        },
      },
      {
        title: "所处区域名称",
        key: "area_name",
        render(row) {
          return h(
            NTag,
            { type: "warning", bordered: false },
            row.area_name
          );
        },
      },
      {
        title: "电动车此时状态",
        key: "status",
        render(row) {
          let statusType = "default";
          let statusText = "未知";
          switch (row.status) {
            case 0:
              statusType = "warning";
              statusText = "正在骑行中";
              break;
            case 1:
              statusType = "success";
              statusText = "空闲中";
              break;
            case 2:
              statusType = "error";
              statusText = "异常状态";
              break;
            case 3:
              statusType = "info";
              statusText = "停止中";
              break;
          }
          return h(
            NTag,
            { type: statusType, bordered: false },
            statusText
          );
        },
      },
      {
      title: '操作',
      key: 'actions',
      render(rowData) {
        return h('div', [
         h(
          NIconWrapper,
          {
          color: 'blue',
          style: 'margin-right:15px',
          onClick: () => {
            dialog.info({
              title:'骑行电动车',
              content: () => createVNode(MachineStart,{machineId: rowData.machine_id,machine_point:rowData.machine_point})
            })
          },
        },
          { default: () => h(NIcon, { component: Motorbike})}
        ),
        h(
          NIconWrapper,
          { color:'red',
            style:'margin-right:15px',
            onClick: () => {
              deleteMachine(rowData.machine_id)
          },   
          },
          { default: () => h(NIcon, { component: TrashOff}) }
        ),
        h(
          NIconWrapper,
          { color:'orange',
            style:'margin-right:15px',  
          },
          { default: () => h(NIcon, { component: CloudUpload}) }
        )
        ]);
      },
    },
    ];
  }
  
  // 响应式数据
  const machineList = reactive([]);
  const maxpage = ref(0);
  const loading = ref(false);

  
  // 分页配置
  const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [3, 5, 10],
    onChange(page) {
      loading.value = true;
      if (page > paginationReactive.page && page > maxpage.value) {
        paginationReactive.page = page;
        fetchMachineList(page, paginationReactive.pageSize);
      } else {
        paginationReactive.page = page;
        loading.value = false;
      }
    },
    onUpdatePageSize(pageSize) {
      paginationReactive.pageSize = pageSize;
      paginationReactive.page = 1;
    },
  });
  
  // 获取电动车列表数据
  const fetchMachineList = async () => {
    try {
      loading.value = true;
      const data = {
      'page':1,
      'page_size':500
    }
    // 如果有选择q区域，加入 area_id 参数
    if (selectedArea.value !== null) {
      data.area_id = selectedArea.value;
    }

    // 如果有选择电动车状态，加入 status 参数
    if (selectedStatus.value !== null) {
      data.status = selectedStatus.value;
    }

    // 如果有输入电动车编号，加入 user_id 参数
    if (query.value) {
      data.machine_id = query.value;
    }
      const response = await axiosInstance.post("/api/machine_list", 
        data,
      );
  
      if (response.data.success) {
        machineList.length = 0
        machineList.push(...response.data.data);
        maxpage.value = Math.ceil(response.data.total / paginationReactive.pageSize);
      } else {
        console.error("没有电动车数据");
      }
    } catch (error) {
      console.error("请求失败", error);
    } finally {
      loading.value = false;
    }
  };
  
  // 添加电动车的函数
  const addMachine = async () => {
    // 验证表单
    const valid = await formRef.value.validate();
    if (!valid) return;

    const machineData = {
      machine_point: {
        longitude: formData.machineLongitude,
        latitude: formData.machineLatitude,
      },
    };

    try {
      const response = await axiosInstance.post("/api/machine_add", machineData);
      if (response.data.success) {
        sendMessage("success","电动车添加成功")
        showModal.value = false;
        // 重置表单数据
        formData.machineLongitude = "";
        formData.machineLatitude = "";
        machineList.length = 0
        fetchMachineList()
      } 
      else {
        sendMessage("error",response.data.message)
      }
    } catch (error) {
      sendMessage("error","请求失败")
    }
  };
  // 删除电动车
  const deleteMachine = async (machineId) => {
  try {
    const response = await axiosInstance.get(`/api/machine_delete`, {
      params: { machine_id: machineId }
    });

    if (response.data.success) {
      // 删除成功，刷新电动车列表
      sendMessage("success", "电动车删除成功");
      fetchMachineList();
    } else {
      sendMessage("error", response.data.message || "删除失败");
    }
  } catch (error) {
    sendMessage("error", "请求失败");
  }
};



  // 获取区域数据
const fetchAreaList = async () => {
  try {
    const response = await axiosInstance.post("/api/area_list",{page:1,page_size:500});
    if (response.data.success) {
      areaOptions.length = 0;
      areaOptions.push(...response.data.data.map(area => ({
        label: area.area_name,
        value: area.area_id,
      })));
    } else {
      sendMessage("error", "获取区域数据失败");
    }
  } catch (error) {
    sendMessage("error", "请求失败");
  }
};


  // 初始化页面数据
  onMounted(() => {
    fetchMachineList();
    fetchAreaList()
  });
  
  // 导出CSV功能
  const downloadCsv = () => {
    const columnsForCsv = columns.map((col) => ({
      title: col.title,
      key: col.key,
    }));
  
    const dataForCsv = machineList.map((machine) => {
      const row = {};
      columnsForCsv.forEach((col) => {
        if (col.key === "machine_point") {
          row[col.key] = `经度: ${machine[col.key][0]}, 纬度: ${machine[col.key][1]}`;
        } else if (col.key === "machine_battery") {
          row[col.key] = `${machine[col.key]}%`;
        } else if (col.key === "status") {
          switch (machine[col.key]) {
            case 0:
              row[col.key] = "正在骑行中";
              break;
            case 1:
              row[col.key] = "空闲中";
              break;
            case 2:
              row[col.key] = "处在违规区域";
              break;
            case 3:
              row[col.key] = "停止中";
              break;
            default:
              row[col.key] = "未知";
          }
        } else {
          row[col.key] = machine[col.key];
        }
      });
      return row;
    });
  
    tableRef.value?.downloadCsv({
      fileName: "machine-list",
      data: dataForCsv,
      columns: columnsForCsv,
    });
  };
  </script>
  
  <style scoped>
  .content {
    margin-left: 60px;
    margin-top: 20px;
    height: 1000px;
    width: 1130px;
  }
  .filters {
  display: flex;          
  gap: 20px;             
  margin-bottom: 20px;    
}
  
  </style>